/*
 * BinaryResource.java
 */

package xq.util.resource;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import static xq.util.CommonUtil.choose;
import static xq.util.IOUtil.readData;

/**
 *
 * @author ThorntonRP
 */
public class BinaryResource extends AbstractResource<byte[]> {
	
	private static final long serialVersionUID = -7342820746841935889L;
	
	private byte[] content;

	public BinaryResource(String contentURI, String contentType, byte[] content) throws URISyntaxException {
		super(contentURI, choose(contentType, "application/octet-stream"));
		this.content = content;
	}
	
	public BinaryResource(URI contentURI, String contentType, byte[] content) {
		super(contentURI, choose(contentType, "application/octet-stream"));
	}
	
	public BinaryResource(URL resourceURL, String contentType) throws IOException {
		super(resourceURL, choose(contentType, choose(resourceURL.openConnection().getContentType(), "application/octet-stream")));
	}

	public BinaryResource(File resourceFile, String contentType) throws IOException {
		super(resourceFile, choose(contentType, choose(resourceFile.toURI().toURL().openConnection().getContentType(), "application/octet-stream")));
	}

	@Override
	public byte[] getContent() throws IOException {
		if (content == null) {
			if (getResourceFile() == null) {
				content = readData(getResourceURL());
			} else {
				content = readData(getResourceFile());
			}
		}
		return content;
	}
}
